//
//  VideoRecordView.m
//  for_test
//
//  Created by Carlson Lee on 2017/4/5.
//  Copyright © 2017年 Carlson Lee. All rights reserved.
//

#import "VideoRecordView.h"

@interface VideoRecordView ()<AVCaptureFileOutputRecordingDelegate>

@property(nonatomic, strong)AVCaptureSession* captureSession;
@property(nonatomic, strong)AVCaptureDeviceInput* captureInput;

@property (strong,nonatomic) AVCaptureMovieFileOutput *captureFileOutput;

@end

@implementation VideoRecordView

- (instancetype)init
{
    if(self = [super init]){
        [self creatSession];//创建会话
    }
    return self;
}

- (AVCaptureVideoPreviewLayer *)captureLayer
{
    if(!_captureLayer){
        _captureLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.captureSession];
        _captureLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.layer addSublayer:_captureLayer];
    }
    return _captureLayer;
}

- (AVCaptureSession *)captureSession
{
    if(!_captureSession){
        _captureSession = [[AVCaptureSession alloc]init];
        if([_captureSession canSetSessionPreset:AVCaptureSessionPresetMedium]){
            _captureSession.sessionPreset = AVCaptureSessionPresetMedium;
        }
    }
    return _captureSession;
}

- (void)creatSession
{
    NSError* error = nil;
    if(!_captureInput){
        AVCaptureDevice *captureDevice=[self getCameraDeviceWithPosition:AVCaptureDevicePositionFront];
        if(!captureDevice)NSAssert(captureDevice, @"获取设备失败");
        _captureInput = [[AVCaptureDeviceInput alloc] initWithDevice:captureDevice error:&error];
        if(error)NSAssert(error, @"初始化设备失败");
    }
    
    AVCaptureDevice *audioCaptureDevice=[[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
    AVCaptureDeviceInput *audioCaptureInput=[[AVCaptureDeviceInput alloc]initWithDevice:audioCaptureDevice error:&error];
    if(error)NSAssert(error, @"初始化音频设备失败");
    
    _captureFileOutput = [[AVCaptureMovieFileOutput alloc]init];;
    if ([self.captureSession canAddInput:_captureInput]) {
        [self.captureSession addInput:_captureInput];
        [self.captureSession addInput:audioCaptureInput];
        AVCaptureConnection *captureConnection=[_captureFileOutput connectionWithMediaType:AVMediaTypeVideo];
        if ([captureConnection isVideoStabilizationSupported ]) {
            captureConnection.preferredVideoStabilizationMode=AVCaptureVideoStabilizationModeAuto;
        }
    }
    
    if ([_captureSession canAddOutput:_captureFileOutput]) {
        [_captureSession addOutput:_captureFileOutput];
    }
    
    [self.captureSession startRunning];
}

-(AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition )position{
    NSArray *cameras= [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *camera in cameras) {
        if ([camera position]==position) {
            return camera;
        }
    }
    return nil;
}

- (void)openSession:(BOOL )isOpen
{
    if(isOpen){
        [self.captureSession startRunning];
        [self setAlpha:1.0];
    }else{
        if(_isRecording){
            [self startRecord:NO];
        }
        [self.captureSession stopRunning];
        [self setAlpha:0.0];
    }
}

- (void)startRecord:(BOOL )isRecord
{
    if(!_isRecording){
        AVCaptureConnection *captureConnection = [self.captureFileOutput connectionWithMediaType:AVMediaTypeVideo];
        if([self.captureFileOutput isRecording]){
            [self.captureFileOutput stopRecording];
            return;
        }
        
        captureConnection.videoOrientation = [self.captureLayer connection].videoOrientation;
        
        NSString *path = [NSTemporaryDirectory() stringByAppendingString:@"videoInfo.mov"];
        NSURL *url = [NSURL fileURLWithPath:path];
        [self.captureFileOutput startRecordingToOutputFileURL:url recordingDelegate:self];
    }else{
        [self.captureFileOutput stopRecording];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.captureLayer.frame = self.bounds;
}

#pragma mark ------ AVCaptureFileOutputRecordingDelegate

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections
{
    _isRecording = YES;
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
    _isRecording = NO;
    
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
{
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
